package com.example.javamaday.common;


import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import Decoder.BASE64Encoder;

public class DESUtils {

    public static void main(String[] args) {
        System.out.println(encrypt("123456", "0001112233334444"));
    }

    public static String encrypt(String data, String key) {
        byte[] bt = encryptByKey(data.getBytes(), key);
        BASE64Encoder base64en = new BASE64Encoder();
        return new String(base64en.encode(bt));
    }

    private static byte[] encryptByKey(byte[] datasource, String key) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            return cipher.doFinal(datasource);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}